package org.jdamico.socks.server.commons;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Utils {

	
	public static InetAddress calcInetAddress(byte[] addr) {
		InetAddress IA = null;
		String sIA = "";

		if (addr.length < 4) {
			DebugLog.getInstance().error("calcInetAddress() - Invalid length of IP v4 - " + addr.length + " bytes");
			return null;
		}

		for (int i = 0; i < 4; i++) {
			sIA += byte2int(addr[i]);
			if (i < 3)
				sIA += ".";
		}

		try {
			IA = InetAddress.getByName(sIA);
		} catch (UnknownHostException e) {
			return null;
		}
		return IA; // IP Address
	}

	public static int byte2int(byte b) {
		int res = b;
		if (res < 0)
			res = (int) (0x100 + res);
		return res;
	}

	public static int calcPort(byte Hi, byte Lo) {
		return ((byte2int(Hi) << 8) | byte2int(Lo));
	}

	public static String iP2Str(InetAddress IP) {
		if (IP == null)
			return "NA/NA";
		return IP.getHostName() + "/" + IP.getHostAddress();
	}

	public static String getSocketInfo(Socket sock) {

		if (sock == null)
			return "<NA/NA:0>";

		return "<" + Utils.iP2Str(sock.getInetAddress()) + ":" + sock.getPort() + ">";
	}

	public static String getSocketInfo(DatagramPacket DGP) {
		if (DGP == null)
			return "<NA/NA:0>";
		return "<" + Utils.iP2Str(DGP.getAddress()) + ":" + DGP.getPort() + ">";
	}

	public static String getCommandName(byte code) {

		switch (code) {
		case 0x01:
			return "CONNECT";
		case 0x02:
			return "BIND";
		case 0x03:
			return "UDP Association";
		default:
			return "Unknown Command";
		}

	}
	
	
	public	 static String	getReplyName( byte code )	{
	
		switch( code )	{
		case 0: return "SUCCESS";
		case 1: return "General SOCKS Server failure";
		case 2: return "Connection not allowed by ruleset";
		case 3: return "Network Unreachable";
		case 4: return "HOST Unreachable";
		case 5: return "Connection Refused";
		case 6: return "TTL Expired";
		case 7: return "Command not supported";
		case 8: return "Address Type not Supported";
		case 9: return "to 0xFF UnAssigned";
		
		case 90: return "Request GRANTED";
		case 91: return "Request REJECTED or FAILED";
		case 92: return "Request REJECTED - SOCKS server can't connect to Identd on the client";
		case 93: return "Request REJECTED - Client and Identd report diff user-ID";		 
				   
		default:	return "Unknown Command";
		}
	}

}
